import 'package:flutter/material.dart';
import '../utils/responsive_layout.dart';
import '../theme/app_theme.dart';

/**
 * 现代化按钮组件
 * 支持多种样式和交互效果
 */
class ModernButton extends StatefulWidget {
  final String text;
  final VoidCallback? onPressed;
  final IconData? icon;
  final ModernButtonStyle style;
  final ModernButtonSize size;
  final Color? backgroundColor;
  final Color? foregroundColor;
  final bool isLoading;
  final bool fullWidth;
  final EdgeInsetsGeometry? padding;
  final BorderRadius? borderRadius;

  const ModernButton({
    super.key,
    required this.text,
    this.onPressed,
    this.icon,
    this.style = ModernButtonStyle.filled,
    this.size = ModernButtonSize.medium,
    this.backgroundColor,
    this.foregroundColor,
    this.isLoading = false,
    this.fullWidth = false,
    this.padding,
    this.borderRadius,
  });

  @override
  State<ModernButton> createState() => _ModernButtonState();
}

class _ModernButtonState extends State<ModernButton>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  bool _isPressed = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 150),
      vsync: this,
    );
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 0.95,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  /**
   * 按下处理
   */
  void _onTapDown(TapDownDetails details) {
    if (widget.onPressed != null && !widget.isLoading) {
      setState(() {
        _isPressed = true;
      });
      _animationController.forward();
    }
  }

  /**
   * 抬起处理
   */
  void _onTapUp(TapUpDetails details) {
    _resetPress();
  }

  /**
   * 取消处理
   */
  void _onTapCancel() {
    _resetPress();
  }

  /**
   * 重置按压状态
   */
  void _resetPress() {
    if (_isPressed) {
      setState(() {
        _isPressed = false;
      });
      _animationController.reverse();
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDesktop = ResponsiveBreakpoints.isDesktop(context);
    
    return AnimatedBuilder(
      animation: _scaleAnimation,
      builder: (context, child) {
        return Transform.scale(
          scale: _scaleAnimation.value,
          child: _buildButton(context, theme, colorScheme, isDesktop),
        );
      },
    );
  }

  /**
   * 构建按钮
   */
  Widget _buildButton(
    BuildContext context,
    ThemeData theme,
    ColorScheme colorScheme,
    bool isDesktop,
  ) {
    final isEnabled = widget.onPressed != null && !widget.isLoading;
    final buttonColors = _getButtonColors(colorScheme);
    final buttonSize = _getButtonSize(isDesktop);

    return GestureDetector(
      onTapDown: _onTapDown,
      onTapUp: _onTapUp,
      onTapCancel: _onTapCancel,
      onTap: isEnabled ? widget.onPressed : null,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 200),
        width: widget.fullWidth ? double.infinity : null,
        padding: widget.padding ?? buttonSize.padding,
        decoration: BoxDecoration(
          color: buttonColors.backgroundColor,
          borderRadius: widget.borderRadius ?? BorderRadius.circular(12),
          border: widget.style == ModernButtonStyle.outlined
              ? Border.all(
                  color: buttonColors.borderColor ?? Colors.transparent,
                  width: 1.5,
                )
              : null,
          boxShadow: widget.style == ModernButtonStyle.filled && isEnabled
              ? [
                  BoxShadow(
                    color: buttonColors.backgroundColor?.withOpacity(0.3) ?? Colors.transparent,
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ]
              : null,
        ),
        child: Row(
          mainAxisSize: widget.fullWidth ? MainAxisSize.max : MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (widget.isLoading) ...[
              SizedBox(
                width: buttonSize.iconSize,
                height: buttonSize.iconSize,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    buttonColors.foregroundColor,
                  ),
                ),
              ),
              const SizedBox(width: 8),
            ] else if (widget.icon != null) ...[
              Icon(
                widget.icon,
                size: buttonSize.iconSize,
                color: buttonColors.foregroundColor,
              ),
              const SizedBox(width: 8),
            ],
            Text(
              widget.text,
              style: theme.textTheme.labelLarge?.copyWith(
                color: buttonColors.foregroundColor,
                fontSize: buttonSize.fontSize,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /**
   * 获取按钮颜色
   */
  _ButtonColors _getButtonColors(ColorScheme colorScheme) {
    final isEnabled = widget.onPressed != null && !widget.isLoading;
    
    switch (widget.style) {
      case ModernButtonStyle.filled:
        return _ButtonColors(
          backgroundColor: isEnabled
              ? (widget.backgroundColor ?? colorScheme.primary)
              : colorScheme.onSurface.withOpacity(0.12),
          foregroundColor: isEnabled
              ? (widget.foregroundColor ?? colorScheme.onPrimary)
              : colorScheme.onSurface.withOpacity(0.38),
        );
      
      case ModernButtonStyle.outlined:
        return _ButtonColors(
          backgroundColor: Colors.transparent,
          foregroundColor: isEnabled
              ? (widget.foregroundColor ?? colorScheme.primary)
              : colorScheme.onSurface.withOpacity(0.38),
          borderColor: isEnabled
              ? (widget.backgroundColor ?? colorScheme.primary)
              : colorScheme.onSurface.withOpacity(0.12),
        );
      
      case ModernButtonStyle.text:
        return _ButtonColors(
          backgroundColor: Colors.transparent,
          foregroundColor: isEnabled
              ? (widget.foregroundColor ?? colorScheme.primary)
              : colorScheme.onSurface.withOpacity(0.38),
        );
      
      case ModernButtonStyle.tonal:
        return _ButtonColors(
          backgroundColor: isEnabled
              ? (widget.backgroundColor ?? colorScheme.secondaryContainer)
              : colorScheme.onSurface.withOpacity(0.12),
          foregroundColor: isEnabled
              ? (widget.foregroundColor ?? colorScheme.onSecondaryContainer)
              : colorScheme.onSurface.withOpacity(0.38),
        );
    }
  }

  /**
   * 获取按钮尺寸
   */
  _ButtonSize _getButtonSize(bool isDesktop) {
    switch (widget.size) {
      case ModernButtonSize.small:
        return _ButtonSize(
          padding: EdgeInsets.symmetric(
            horizontal: isDesktop ? 12 : 16,
            vertical: isDesktop ? 6 : 8,
          ),
          fontSize: isDesktop ? 12 : 14,
          iconSize: isDesktop ? 16 : 18,
        );
      
      case ModernButtonSize.medium:
        return _ButtonSize(
          padding: EdgeInsets.symmetric(
            horizontal: isDesktop ? 16 : 20,
            vertical: isDesktop ? 10 : 12,
          ),
          fontSize: isDesktop ? 14 : 16,
          iconSize: isDesktop ? 18 : 20,
        );
      
      case ModernButtonSize.large:
        return _ButtonSize(
          padding: EdgeInsets.symmetric(
            horizontal: isDesktop ? 20 : 24,
            vertical: isDesktop ? 14 : 16,
          ),
          fontSize: isDesktop ? 16 : 18,
          iconSize: isDesktop ? 20 : 22,
        );
    }
  }
}

/**
 * 现代化图标按钮组件
 */
class ModernIconButton extends StatefulWidget {
  final IconData icon;
  final VoidCallback? onPressed;
  final String? tooltip;
  final ModernButtonSize size;
  final Color? backgroundColor;
  final Color? foregroundColor;
  final bool isSelected;

  const ModernIconButton({
    Key? key,
    required this.icon,
    this.onPressed,
    this.tooltip,
    this.size = ModernButtonSize.medium,
    this.backgroundColor,
    this.foregroundColor,
    this.isSelected = false,
  }) : super(key: key);

  @override
  State<ModernIconButton> createState() => _ModernIconButtonState();
}

class _ModernIconButtonState extends State<ModernIconButton>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  bool _isPressed = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 150),
      vsync: this,
    );
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 0.9,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  /**
   * 按下处理
   */
  void _onTapDown(TapDownDetails details) {
    if (widget.onPressed != null) {
      setState(() {
        _isPressed = true;
      });
      _animationController.forward();
    }
  }

  /**
   * 抬起处理
   */
  void _onTapUp(TapUpDetails details) {
    _resetPress();
  }

  /**
   * 取消处理
   */
  void _onTapCancel() {
    _resetPress();
  }

  /**
   * 重置按压状态
   */
  void _resetPress() {
    if (_isPressed) {
      setState(() {
        _isPressed = false;
      });
      _animationController.reverse();
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDesktop = ResponsiveBreakpoints.isDesktop(context);
    final isEnabled = widget.onPressed != null;
    
    final buttonSize = _getIconButtonSize(isDesktop);
    final colors = _getIconButtonColors(colorScheme, isEnabled);

    return AnimatedBuilder(
      animation: _scaleAnimation,
      builder: (context, child) {
        return Transform.scale(
          scale: _scaleAnimation.value,
          child: Tooltip(
            message: widget.tooltip ?? '',
            child: GestureDetector(
              onTapDown: _onTapDown,
              onTapUp: _onTapUp,
              onTapCancel: _onTapCancel,
              onTap: isEnabled ? widget.onPressed : null,
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 200),
                width: buttonSize,
                height: buttonSize,
                decoration: BoxDecoration(
                  color: colors.backgroundColor,
                  borderRadius: BorderRadius.circular(buttonSize / 2),
                  boxShadow: widget.isSelected
                      ? [
                          BoxShadow(
                            color: colors.backgroundColor?.withOpacity(0.3) ?? Colors.transparent,
                            blurRadius: 8,
                            offset: const Offset(0, 2),
                          ),
                        ]
                      : null,
                ),
                child: Icon(
                  widget.icon,
                  size: buttonSize * 0.5,
                  color: colors.foregroundColor,
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /**
   * 获取图标按钮尺寸
   */
  double _getIconButtonSize(bool isDesktop) {
    switch (widget.size) {
      case ModernButtonSize.small:
        return isDesktop ? 32 : 36;
      case ModernButtonSize.medium:
        return isDesktop ? 40 : 44;
      case ModernButtonSize.large:
        return isDesktop ? 48 : 52;
    }
  }

  /**
   * 获取图标按钮颜色
   */
  _ButtonColors _getIconButtonColors(ColorScheme colorScheme, bool isEnabled) {
    if (widget.isSelected) {
      return _ButtonColors(
        backgroundColor: widget.backgroundColor ?? colorScheme.primaryContainer,
        foregroundColor: widget.foregroundColor ?? colorScheme.onPrimaryContainer,
      );
    }

    return _ButtonColors(
      backgroundColor: isEnabled
          ? (widget.backgroundColor ?? colorScheme.surfaceContainerHighest.withOpacity(0.5))
          : colorScheme.onSurface.withOpacity(0.12),
      foregroundColor: isEnabled
          ? (widget.foregroundColor ?? colorScheme.onSurface)
          : colorScheme.onSurface.withOpacity(0.38),
    );
  }
}

/**
 * 按钮颜色配置
 */
class _ButtonColors {
  final Color backgroundColor;
  final Color foregroundColor;
  final Color? borderColor;

  _ButtonColors({
    required this.backgroundColor,
    required this.foregroundColor,
    this.borderColor,
  });
}

/**
 * 按钮尺寸配置
 */
class _ButtonSize {
  final EdgeInsetsGeometry padding;
  final double fontSize;
  final double iconSize;

  _ButtonSize({
    required this.padding,
    required this.fontSize,
    required this.iconSize,
  });
}

/**
 * 按钮样式枚举
 */
enum ModernButtonStyle {
  filled,   // 填充样式
  outlined, // 边框样式
  text,     // 文本样式
  tonal,    // 色调样式
}

/**
 * 按钮尺寸枚举
 */
enum ModernButtonSize {
  small,   // 小尺寸
  medium,  // 中等尺寸
  large,   // 大尺寸
}